//
//  ProductDetailsViewController.m
//  WorkNest
//
//  Created by qbm360 on 15/7/20.
//  Copyright (c) 2015年 nest. All rights reserved.
//

#import "ProductDetailsViewController.h"
#import "PlatformCell.h"
#import "OrderCountView.h"
#import "OrderDetailViewController.h"
#import "ApplyRecommendViewController.h"
#import "ProductDetailModel.h"
#import "BulkorderModel.h"
#import "PriceQueryChooseViewController.h"
#import "AddressViewController.h"
#import "AddressModel.h"
#import "PlatformDetailCell.h"

static NSString *PlatformCellIdentifier = @"PlatformCell";
static NSString *PlatformDetailCellIdentifier = @"PlatformDetailCell";

@interface ProductDetailsViewController () <UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITableView *myTableView;
@property (weak, nonatomic) IBOutlet UIButton *applyRecommend;
@property (strong, nonatomic) NSArray *style;
@property (strong, nonatomic) UIView *countView;
@property (nonatomic, strong) ProductDetailModel *detailModel;
@property (nonatomic, strong) NSArray *colorArray;
@property (nonatomic, strong) NSArray *sizeArray;
@property (nonatomic, strong) NSMutableArray *designArray;
@property (nonatomic, strong) BulkorderModel *bulkorderModel;
@property (nonatomic, strong) AddressModel *addressModel;
@property (nonatomic, strong) NSString *addressIndex;
@property (nonatomic, strong) NSIndexPath *countPath;

@end

@implementation ProductDetailsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"产品详情";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"collection"] style:UIBarButtonItemStyleBordered target:self action:@selector(collectionProduct)];
    _bulkorderModel = [[BulkorderModel alloc] init];
    [self.myTableView registerNib:[UINib nibWithNibName:@"PlatformCell" bundle:nil]
           forCellReuseIdentifier:PlatformCellIdentifier];
    [self.myTableView registerNib:[UINib nibWithNibName:@"PlatformDetailCell" bundle:nil]
           forCellReuseIdentifier:PlatformDetailCellIdentifier];
    [self requestData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)requestData {
    NSDictionary *dic = @{@"userName":[UserModel sharedInstance].userName, @"token":[UserModel sharedInstance].userToken, @"productId":_productId==nil?@"":_productId};
    [RequestData getProductDetail:[UIUtil toJsonString:dic] withBlock:^(ProductDetailModel *model, NSString *msg, NSError *error) {
        if (error) {
            if ([msg isEqualToString:@"9001"] || [msg isEqualToString:@"9002"]) {
                [UIUtil tokenOverdue:self msg:msg];
            } else {
                [[ESHUDView sharedInstance] showErrorMessage:msg==nil?@"请求失败":msg dismissBlock:nil];
            }
        } else {
            self.detailModel = model;
        }
    }];
}

- (void)setDetailModel:(ProductDetailModel *)detailModel {
    _detailModel = detailModel;
    if (_ifMyProduct) {
        if (self.productStatus) {
            self.applyRecommend.hidden = NO;
            if ([self.productStatus integerValue] == 1 || [self.productStatus integerValue] == 2) {
                [self.applyRecommend setTitle:@"上架" forState:UIControlStateNormal];
            } else if ([self.productStatus integerValue] == 4) {
                [self.applyRecommend setTitle:@"下架" forState:UIControlStateNormal];
            } else if ([self.productStatus integerValue] == 8) {
                [self.applyRecommend setTitle:@"申请中" forState:UIControlStateNormal];
            }
        } else {
            self.applyRecommend.hidden = YES;
        }
    } else {
        self.applyRecommend.hidden = YES;
    }
    _colorArray = [_detailModel.color componentsSeparatedByString:@";"];
    _sizeArray = [_detailModel.size componentsSeparatedByString:@";"];
    NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:_colorArray.count*_sizeArray.count];
    _designArray = [[NSMutableArray alloc] init];
    for (int i=0; i<_colorArray.count; i++) {
        for (int j=0; j<_sizeArray.count; j++) {
            [array addObject:[NSString stringWithFormat:@"%@/%@",_colorArray[i],_sizeArray[j]]];
            [_designArray addObject:@{@"color":_colorArray[i],@"size":_sizeArray[j],@"quantity":@"0"}];
        }
    }
    self.style = array;
    _bulkorderModel.productId = _detailModel.productId;
    _bulkorderModel.productName = _detailModel.productName;
    _bulkorderModel.numList = _designArray;
    _bulkorderModel.imageList = _detailModel.imageList;
    if (_detailModel.MainImange && ![_detailModel.MainImange isEqualToString:@""]) {
        _bulkorderModel.mainImage = _detailModel.MainImange;
    } else if (_bulkorderModel.imageList.count >0) {
        _bulkorderModel.mainImage = _detailModel.imageList[0];
    }
    _bulkorderModel.productType = _detailModel.productType;
    [self creatStyle];
    [self.myTableView reloadData];
}

- (void)creatStyle {
    _countView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT, self.view.frame.size.width, (self.style.count + 2) * 28)];
    _countView.backgroundColor = [UIColor whiteColor];
    _countView.layer.borderWidth = 1;
    _countView.layer.borderColor = [[UIUtil colorWithHexString:@"#bdbaba"] CGColor];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(SCREEN_WIDTH - 30, 0, 30, 25);
    [button setTitle:@"确定" forState:UIControlStateNormal];
    [button setTitleColor:[UIUtil colorWithHexString:@"#5f5f5f"] forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:12];
    [button addTarget:self action:@selector(shutDownView) forControlEvents:UIControlEventTouchUpInside];
    [self.countView addSubview:button];
    for (int i = 0; i < self.style.count + 1; i++) {
        if (i == 0) {
            OrderCountView *countView = [[OrderCountView alloc] initWithFrame:CGRectMake(24, 28, SCREEN_WIDTH - 48, 28) ifFirstView:YES];
            countView.styleString = @"款式";
            countView.layer.borderWidth = 1;
            countView.layer.borderColor = [[UIUtil colorWithHexString:@"#bdbaba"] CGColor];
            [_countView addSubview:countView];
        } else  {
            OrderCountView *countView = [[OrderCountView alloc] initWithFrame:CGRectMake(24, 28 * i - (1 + i) + 28, SCREEN_WIDTH - 48, 28) ifFirstView:NO];
            countView.styleString = [self.style objectAtIndex:i-1];
            countView.countString = [[_designArray objectAtIndex:i-1] valueForKey:@"quantity"];
            countView.index = i-1;
            countView.layer.borderWidth = 1;
            countView.layer.borderColor = [[UIUtil colorWithHexString:@"#bdbaba"] CGColor];
            [_countView addSubview:countView];
            countView.editBlock = ^(BOOL ifEdit, NSInteger hight) {
                if (ifEdit) {
                    [UIView animateWithDuration:0.5 animations:^{
                        _countView.frame = CGRectMake(0, self.view.frame.size.height - ((self.style.count + 2) * 28) - hight, SCREEN_WIDTH, (self.style.count + 2) * 28);
                    }];
                } else {
                    [UIView animateWithDuration:0.5 animations:^{
                        _countView.frame = CGRectMake(0, self.view.frame.size.height - ((self.style.count + 2) * 28) - 47, SCREEN_WIDTH, (self.style.count + 2) * 28);
                    }];
                }
            };
            countView.countBlock =^(NSInteger index, NSString *count) {
                [_designArray replaceObjectAtIndex:index withObject:@{@"color":[_designArray[index] valueForKey:@"color"], @"size":[_designArray[index] valueForKey:@"size"], @"quantity":count}];
            };
        }
    }
    [self.view addSubview:_countView];
}

#pragma mark - action methods
- (IBAction)applyRecommend:(id)sender {
    if ([self.productStatus integerValue] == 4) {
        NSDictionary *dic = @{@"userName":[UserModel sharedInstance].userName, @"token":[UserModel sharedInstance].userToken, @"productId":_productId==nil?@"":_productId,@"type":@"0"};
        [RequestData productApply:[UIUtil toJsonString:dic] withBlock:^(NSString *msg, NSError *error) {
            if (error) {
                if ([msg isEqualToString:@"9001"] || [msg isEqualToString:@"9002"]) {
                    [UIUtil tokenOverdue:self msg:msg];
                } else {
                    [[ESHUDView sharedInstance] showErrorMessage:msg==nil?@"下架失败":msg dismissBlock:nil];
                }
            } else {
                [[ESHUDView sharedInstance] showSuccessMessage:msg dismissBlock:nil];
            }
        }];
    } else {
        ApplyRecommendViewController *view = [[ApplyRecommendViewController alloc] init];
        view.productId = _productId;
        [self.navigationController pushViewController:view animated:YES];
    }
}

- (IBAction)addShoppingCart:(id)sender {
    NSInteger count = 0;
    for (int i=0; i<self.designArray.count; i++) {
        count = count + [[self.designArray[i] valueForKey:@"quantity"] integerValue];
    }
    if (count - [_detailModel.minOrderNumber integerValue]<0) {
        [[ESHUDView sharedInstance] showErrorMessage:[NSString stringWithFormat:@"最小下单数量不得少于%@", _detailModel.minOrderNumber] dismissBlock:nil];
        return;
    }
    NSString *price = [self.detailModel.optOrderNumber integerValue] - count > 0 ?self.detailModel.quotation:self.detailModel.quotation2;
    _bulkorderModel.perPrice = price;
    _bulkorderModel.totalPrice = [NSString stringWithFormat:@"%.2f",[price floatValue]*count];
    _bulkorderModel.totalQuantity = [NSString stringWithFormat:@"%li", (long)count];
    if (!_bulkorderModel.requiredExplain || !_bulkorderModel.deliveryTime || !_bulkorderModel.deliveryWay || !_bulkorderModel.userReceiveAddress) {
        [[ESHUDView sharedInstance] showErrorMessage:@"信息不完整" dismissBlock:nil];
        return;
    }
    NSDictionary *dic = @{@"userName":[UserModel sharedInstance].userName,
                             @"token":[UserModel sharedInstance].userToken,
                              @"type":@"1",
                          @"SCRecord":@{ @"productId":_detailModel.productId==nil?@"":_detailModel.productId,
                                         @"productName":_detailModel.productName==nil?@"":_detailModel.productName,
                                         @"totalQuantity":[NSString stringWithFormat:@"%li", (long)count],
                                         @"perPrice":price,
                                         @"totalPrice":[NSString stringWithFormat:@"%.2f",[price floatValue]*count],
                                         @"requiredExplain":_bulkorderModel.requiredExplain==nil?@"":_bulkorderModel.requiredExplain,
                                         @"deliveryTime":_bulkorderModel.deliveryTime==nil?@"":_bulkorderModel.deliveryTime,
                                         @"deliveryWay":_bulkorderModel.deliveryWay==nil?@"":_bulkorderModel.deliveryWay,
                                         @"remark":@"beizhu",
                                         @"userReceiveAddress":_bulkorderModel.userReceiveAddress==nil?@"":_bulkorderModel.userReceiveAddress},
                                         @"dataList":self.designArray};
    [RequestData addShoppingCart:[UIUtil toJsonString:dic] withBlock:^(NSString *msg, NSError *error) {
        if (error) {
            if ([msg isEqualToString:@"9001"] || [msg isEqualToString:@"9002"]) {
                [UIUtil tokenOverdue:self msg:msg];
            } else {
                [[ESHUDView sharedInstance] showErrorMessage:msg==nil?@"加入购物车失败":msg dismissBlock:nil];
            }
        } else {
            [[ESHUDView sharedInstance] showSuccessMessage:msg dismissBlock:nil];
        }
    }];
}

- (IBAction)immediatelyPay:(id)sender {
    NSInteger count = 0;
    for (int i=0; i<self.designArray.count; i++) {
        count = count + [[self.designArray[i] valueForKey:@"quantity"] integerValue];
    }
    NSString *price = [self.detailModel.optOrderNumber integerValue] - count > 0 ?self.detailModel.quotation:self.detailModel.quotation2;
    _bulkorderModel.perPrice = price;
    _bulkorderModel.totalPrice = [NSString stringWithFormat:@"%.2f",[price floatValue]*count];
    _bulkorderModel.totalQuantity = [NSString stringWithFormat:@"%li", (long)count];
    if (!_bulkorderModel.requiredExplain || !_bulkorderModel.deliveryTime || !_bulkorderModel.deliveryWay) {
        [[ESHUDView sharedInstance] showErrorMessage:@"信息不完整" dismissBlock:nil];
        return;
    }
    OrderDetailViewController *view = [[OrderDetailViewController alloc] init];
    view.bulkorderModel = _bulkorderModel;
    view.ifPay = YES;
    view.orderTitle = @"订单详情";
    view.style = self.style;
    view.productDetailModel = _detailModel;
    [self.navigationController pushViewController:view animated:YES];
}

- (void)collectionProduct {
    NSDictionary *dic = @{@"userName":[UserModel sharedInstance].userName, @"token":[UserModel sharedInstance].userToken, @"productId":_productId==nil?@"":_productId,@"remark":@"",@"type":@"1"};
    [RequestData productCollect:[UIUtil toJsonString:dic] withBlock:^(NSString *msg, NSError *error) {
        if (error) {
            if ([msg isEqualToString:@"9001"] || [msg isEqualToString:@"9002"]) {
                [UIUtil tokenOverdue:self msg:msg];
            } else {
                [[ESHUDView sharedInstance] showErrorMessage:msg==nil?@"收藏失败":msg dismissBlock:nil];
            }
        } else {
            [[ESHUDView sharedInstance] showSuccessMessage:msg == nil?@"收藏成功":msg dismissBlock:nil];
        }
    }];
}

- (void)shutDownView {
    [self.view endEditing:YES];
//    [UIView animateWithDuration:0.5 animations:^{
        _countView.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, (self.style.count + 2) * 28);
//    }];
    [_countView removeFromSuperview];
    NSInteger count = 0;
    for (int i=0; i<self.designArray.count; i++) {
        count = count + [[self.designArray[i] valueForKey:@"quantity"] integerValue];
    }
    [self.myTableView cellForRowAtIndexPath:_countPath].detailTextLabel.text = [NSString stringWithFormat:@"%ld",(long)count];
}

- (void)showCountView {
//    [UIView animateWithDuration:0.5 animations:^{
        //            _countView.frame = CGRectMake(0, self.view.frame.size.height - ((self.style.count + 2) * 28) - 47, SCREEN_WIDTH, (self.style.count + 2) * 28);
        _countView.frame = CGRectMake(0, self.view.frame.size.height-_countView.frame.size.height-47, SCREEN_WIDTH, _countView.frame.size.height);
        [self.view addSubview:_countView];
//    }];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 7;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        PlatformCell *cell = [tableView dequeueReusableCellWithIdentifier:PlatformCellIdentifier];
        if (cell == nil) {
            cell = [[PlatformCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:PlatformCellIdentifier];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.ifMyProduct = _ifMyProduct;
        cell.model = self.detailModel;
        return cell;
    } else if (indexPath.row == 1) {
        PlatformDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:PlatformDetailCellIdentifier];
        if (cell == nil) {
            cell = [[PlatformDetailCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:PlatformDetailCellIdentifier];
        }
        cell.model = self.detailModel;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    else {
        NSArray *array = @[@"选择款式数量",@"订单详细要求",@"选择收货地址",@"要求交货日期",@"订单物流方式"];
        UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:nil];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(15, 20, 10 , 10)];
        label.textColor = [UIColor redColor];
        label.text = @"*";
        label.font = [UIFont systemFontOfSize:15];
        [cell addSubview:label];
        
        cell.textLabel.font = [UIFont systemFontOfSize:14];
        cell.detailTextLabel.font = [UIFont systemFontOfSize:13];
        cell.textLabel.textColor = [UIUtil colorWithHexString:@"#5f5f5f"];
        cell.textLabel.text = [NSString stringWithFormat:@"  %@",[array objectAtIndex:indexPath.row-2]];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        return cell;
    }
}

#pragma mark - Table view delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        return (SCREEN_WIDTH*265/320)+92;
    } else if (indexPath.row == 1) {
        return 169;
    } else {
        return 44;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self.myTableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 2) {
        [self showCountView];
        _countPath = indexPath;
    } else if (indexPath.row == 3) {
        PriceQueryChooseViewController *view = [[PriceQueryChooseViewController alloc] init];
        view.choose = @"1";
        view.positionArray = @[@"",@"",@"订单详细要求"];
//        _bulkorderModel.requiredExplain = @"需求";//
        view.chooseBlock = ^(NSString *title) {
            _bulkorderModel.requiredExplain = title;
            [self.myTableView cellForRowAtIndexPath:indexPath].detailTextLabel.text = title;
        };
        view.detailText = _bulkorderModel.requiredExplain;
        [self.navigationController pushViewController:view animated:YES];
    } else if (indexPath.row == 4) {
        AddressViewController *view = [[AddressViewController alloc] init];
        view.addressTitle = @"选择收货地址";
        view.addressIndex = self.addressIndex;
        view.chooseAddressBlock = ^(AddressModel *model, NSString *index) {
            _bulkorderModel.userReceiveAddress = model.addressId;
            self.addressIndex = index;
            [self.myTableView cellForRowAtIndexPath:indexPath].detailTextLabel.text = [NSString stringWithFormat:@"%@%@%@%@",model.province,model.city,model.district,model.address];
        };
        view.ifModify = NO;
        [self.navigationController pushViewController:view animated:YES];
    } else if (indexPath.row == 5) {
        PriceQueryChooseViewController *view = [[PriceQueryChooseViewController alloc] init];
        view.choose = @"0";
        view.ifChooseDate = YES;
        view.positionArray = @[@"",@"",@"要求交货日期"];
        view.chooseBlock = ^(NSString *title) {
            _bulkorderModel.deliveryTime = title;
            [self.myTableView cellForRowAtIndexPath:indexPath].detailTextLabel.text = title;
        };
        view.detailText = _bulkorderModel.deliveryTime;
        [self.navigationController pushViewController:view animated:YES];
    } else if (indexPath.row == 6) {
        PriceQueryChooseViewController *view = [[PriceQueryChooseViewController alloc] init];
        view.choose = @"2";
        view.ifChooseWay = YES;
        view.positionArray = @[@"",@"",@"订单物流方式"];
        view.chooseBlock = ^(NSString *title) {
            _bulkorderModel.deliveryWay = title;
            [self.myTableView cellForRowAtIndexPath:indexPath].detailTextLabel.text = title;
        };
        view.detailText = _bulkorderModel.deliveryWay;
        [self.navigationController pushViewController:view animated:YES];
    }
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

@end
